import 'package:flutter/material.dart';

extension StringExtension on String {
  int get toInt {
    return int.parse('${this}');
  }

  double get toDouble {
    return double.parse('${this ?? '0.00'}');
  }

  bool get toBoolean {
    return this != null && this.isNotEmpty;
  }

  String get formatString {
    if (this.toInt < 10000) {
      return this;
    } else {
      double d = this.toDouble / 1000;
      int i = d.round();
      d = i.toInt() / 10.0;
      return '{$d}万';
    }
  }

  bool get empty {
    return this == null || this.isEmpty;
  }

  bool get notEmpty{
    return this != null && this.isNotEmpty;
  }

  /// double类型字符串格式化，确保double后最多精确两位
  String get formatDoubleString {
    if(this.contains('.')) {
      List<String> splits = this.split('.');
      if (splits.last.length > 2) {
        splits.last = splits.last.substring(0,2);
      }
      return splits.first + splits.last;
    }
    return this;
  }

  /// 百分比字符串转double类型
  double get percentToDouble{
    double result = .0;
    if (this.empty) return result;
    String percentStr = this.replaceAll("%", "");
    try {
      double percentDouble = double.parse(percentStr);
      result = percentDouble / 100;
    } catch (e) {
      print(e);
    }
    return result;
  }

  /// 获取字符串尺寸
  Size get sizeWithFont12 {
    return calSizeWithFont(this,12);
  }
  Size get sizeWithFont14 {
    return calSizeWithFont(this,14);
  }
  Size get sizeWithFont16 {
    return calSizeWithFont(this,16);
  }
  Size get sizeWithFont18 {
    return calSizeWithFont(this,18);
  }
  /// 计算尺寸
  static Size calSizeWithFont(String text,double font) {
    TextStyle style = TextStyle(color: Color.fromRGBO(51, 51, 51, 1),
            fontSize: font);
    final TextPainter textPainter = TextPainter(
            text: TextSpan(text: text, style: style),
            maxLines: 1,
            textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.size;
  }

}
